﻿local tablet = AceLibrary("Tablet-2.0")

local L = AceLibrary("AceLocale-2.2"):new("FuBar_LoginTimerFu")

LoginTimerFu = AceLibrary("AceAddon-2.0"):new("FuBarPlugin-2.0", "AceEvent-2.0")

local mod = LoginTimerFu

function mod:OnInitialize()
    self.loginStart = "nil"
    self.loginSec = 0
		self.name = "LoginTimeFu"
		self.msgHour = L["Hour"]
		self.msgMinute = L["Minute"]
		self.msgSecond = L["Second"]
		self.msgLoginat = L["Loginat"]
end

function mod:OnEnable()
	self:RegisterEvent("PLAYER_LOGOUT", "OnLoginTimerDisabled")
	self:RegisterEvent("PLAYER_LOGIN", "OnLoginTimerEnabled")
	self:ScheduleRepeatingEvent(self.name, self.Update, 1, self)
end

function mod:OnDisable()
	self:UnRegisterEvent("PLAYER_LOGOUT")
	self:UnRegisterEvent("PLAYER_LOGIN")
	self:CancelScheduledEvent(self.name)
end


-- Logging out
function mod:OnLoginTimerDisabled()

end

-- Logging in
function mod:OnLoginTimerEnabled()
  self.loginStart = date("%H:%M:%S")
  self.loginSec = GetTime()
	self:Update()
end

function mod:GetCurrentLoginTime()
	local sec = 0
	
	sec = GetTime()-self.loginSec
	
	if(sec < 0) then
		sec = 0
	end
	
	local s = math.floor(sec)
	local lhour = math.floor(s / 3600)
	s = s - lhour * 3600
	local lmin = math.floor(s / 60)
	local lsec = s - lmin * 60
	if lhour == 0 and lmin == 0 and lsec == 0 then
		 return ""
	end
	if lhour == 0 then
	   return ("%d " .. self.msgMinute .. " %d " .. self.msgSecond):format(lmin, lsec)
	end
	return ("%d " .. self.msgHour .. " %d " .. self.msgMinute .. " %d " .. self.msgSecond):format(lhour, lmin, lsec)
end

function mod:OnTextUpdate()
		self:SetText("|cff00ff00".. self:GetCurrentLoginTime() .."|r")
end

function mod:OnTooltipUpdate()
	local cat = tablet:AddCategory(
		'columns', 2,
		'child_textR', 1,
		'child_textG', 1,
		'child_textB', 0,
		'child_text2R', 1,
		'child_text2G', 1,
		'child_text2B', 1
	)
	cat:AddLine(
		'text', self.msgLoginat,
		'text2', self.loginStart
	)
end